package com.zhonghui.service.impl;

import com.zhonghui.common.core.utils.RedisUtils;
import com.zhonghui.common.core.result.FwResult;
import com.zhonghui.dto.CartAddDto;
import com.zhonghui.dto.CartUpdateDto;
import com.zhonghui.mapper.CartMapper;
import com.zhonghui.mapper.ProductMapper;
import com.zhonghui.model.Cart;
import com.zhonghui.model.Product;
import com.zhonghui.service.CartService;
import com.zhonghui.vo.CartListVo;
import com.zhonghui.vo.CartProductVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: FL
 * @create: 2024 2024/5/11 14:54
 */
@Service
@Slf4j
public class CartServiceImpl implements CartService {
    @Autowired
    CartMapper cartMapper;
    @Autowired
    ProductMapper productMapper;

    @Autowired
    RedisUtils redisUtils;

    /**
     * 获取购物车列表
     * @return
     */
    @Override
    public FwResult getCartList() {
        String userIdStr = redisUtils.get("userId");
        if (userIdStr == null || userIdStr.isEmpty()) {
            return FwResult.failedMsg("用户ID不存在");
        }
        Long userId = Long.parseLong(userIdStr);

        List<Cart> cartList = cartMapper.getCartList(userId);
//        缓存
        redisUtils.lSet("cartList", cartList.toString());
        List<CartProductVo> cartListVos = new ArrayList<>();
        // 计算购物车总价
        BigDecimal cartTotalPrice = new BigDecimal(0);
        Integer cartTotalQuantity = 0;
        boolean selectAll = true;

        if (cartList != null && !cartList.isEmpty()) {
            for (Cart cart : cartList) {
                cartTotalPrice = cartTotalPrice.add(cart.getProductTotalPrice());
                if (cart.getSelected() != 1) {
                    selectAll = false;
                }
                cartTotalQuantity += cart.getQuantity();
                cartListVos.add(CartProductVo.builder()
                        .cartId(cart.getId())
                        .productName(cart.getProductName())
                        .productSubtitle(cart.getProductSubTitle())
                        .productImage(cart.getProductMainImage())
                        .productId(cart.getProductId())
                        .productUnitPrice(cart.getProductUnitPrice())
                        .productTotalPrice(cart.getProductTotalPrice())
                        .quantity(cart.getQuantity())
                        .selected(cart.getSelected())
                       .build());
            }

            CartListVo cartListVo = CartListVo.builder()
                    .cartTotalPrice(cartTotalPrice)
                    .cartTotalQuantity(cartTotalQuantity)
                    .selectAll(selectAll)
                    .cartProductList(cartListVos)
                    .build();
            return FwResult.ok(cartListVo);
        } else {
            return FwResult.failedMsg("购物车为空");
        }
    }


    /**
     * 添加购物车
     * @param cartAddDto
     * @return
     */
    @Override
    public FwResult addCart(CartAddDto cartAddDto) {
        //            获取用户id
        String userIdStr = redisUtils.get("userId");
        if (userIdStr == null || userIdStr.isEmpty()) {
            return FwResult.failedMsg("用户ID不存在");
        }
        Long userId = Long.parseLong(userIdStr);
//            获取商品信息
        Product product = productMapper.getProduct(cartAddDto.getProductId());
        if (product != null && product.getStock() > 0) {
//                设置购物车信息

//            考虑购物车中商品是否已经存在、购物车中商品数量是否超过库存
            if (cartAddDto.getQuantity() > product.getStock()) {
                return FwResult.failedMsg("库存不足");
            }
            Cart oldCart = cartMapper.getCartByProductId(userId, cartAddDto.getProductId());
            if ( oldCart !=null) {
                //存在，直接更新数量和总价
                cartMapper.updateCart(
                        Cart.builder()
                                .quantity(cartAddDto.getQuantity()+oldCart.getQuantity())
                                .productTotalPrice(product.getPrice().multiply(new BigDecimal(cartAddDto.getQuantity())))
                                .build(),oldCart.getId());
                return FwResult.okMsg("更新购物车成功");
            }
            Cart cart = Cart.builder()
                    .productId(cartAddDto.getProductId())
                    .productMainImage(product.getMainImage())
                    .productName(product.getName())
                    .productSubTitle(product.getSubTitle())
                    .productUnitPrice(product.getPrice())
                    .productTotalPrice(product.getPrice().multiply(new BigDecimal(cartAddDto.getQuantity())))
                    .quantity(cartAddDto.getQuantity())
                    .selected(1)
                    .userId(userId)
                    .build();

            Integer n= cartMapper.addCart(cart);
            if ( n > 0){
                return FwResult.okMsg("添加成功");
            }
        }
        return FwResult.failedMsg("添加失败");
    }

    /**
     * 修改购物车
     * @param cartUpdateDto
     * @return
     */
    @Override
    public FwResult updateCart(CartUpdateDto cartUpdateDto) {
        Long cartId = cartUpdateDto.getCartId();
//        根据id查询购物车信息
        Cart cart = cartMapper.getCartById(cartId);
        if (cart == null){
            return FwResult.urlNotFoundMsg("购物车为空");
        }
        cart.setId(null);
        cart.setSelected(cartUpdateDto.getSelected());
        Integer quantity = cart.getQuantity();
//增加
        if (cartUpdateDto.getType() == 1) {
            cart.setQuantity(quantity + 1);
        }
        //减少
        else if (cartUpdateDto.getType() == 0) {
            cart.setQuantity(quantity - 1);
        }
        if (cartMapper.updateCart(cart,cartId) > 0) {
            return FwResult.ok();
        }
        return FwResult.failed();
    }

    /**
     * 删除购物车商品
     */
    @Override
    public FwResult deleteCart(Long id){
//        查看购物车是否存在
        Cart cart = cartMapper.getCartById(id);
        if (cart == null){
            return FwResult.urlNotFoundMsg("该商品不存在");
        }
        if (cartMapper.deleteCart(id) > 0) {
            return FwResult.ok();
        }
        return FwResult.failed();
    }

    /**
     * 清空购物车
     */
    @Override
    public FwResult clearCart() {
        String userIdStr = redisUtils.get("userId");
        if (userIdStr == null || userIdStr.isEmpty()) {
            return FwResult.failedMsg("用户ID不存在");
        }
        Long userId = Long.parseLong(userIdStr);
        if (cartMapper.clearCart(userId) > 0) {
            return FwResult.okMsg("清空购物车成功");
        }
        return FwResult.failedMsg("清空购物车失败");
    }

}
